-- LinkAction
-- create by zouyb
-- 链接动作, 在起始位置和目标位置之间播放光效，持续时间为光效的持续时间
-- 对光效要求： 起始点在坐标原点，沿X轴方向排布

LinkAction = class("LinkAction", function()
    return ActionBase.create();
end);

function LinkAction.create(source, target, skillId, linkCount)
    local self = LinkAction.new();
    self.source = source;
	self.target = target;
	self.skillId = skillId;
    self.linkCount = linkCount;
    return self;
end

-- 构造函数
function LinkAction:ctor()
end

-- 开始播放
function LinkAction:play()
    self.fromPos = self.source:getPos();
    self.toPos = self.target:getPos();
    
    local linkEffectId =  SkillM.query(self.skillId, "dbase")["link_effect_id"];
    if linkEffectId == nil then
        return 0;
    end

	-- 计算from和to之间的中心位置
    local fromGrid = UIDungeonMgr:getCurLevel():getAllGrids()[self.fromPos];
    local toGrid = UIDungeonMgr:getCurLevel():getAllGrids()[self.toPos];
    
    local fromPos = fromGrid:convertToWorldSpace(cc.p(0, 0));
    local toPos = toGrid:convertToWorldSpace(cc.p(0, 0));
    
    local effectParent = UIDungeonMgr:getCurLevel():getEffectParent();
    local targetPos = effectParent:convertToNodeSpace(fromPos);
    
    -- 计算水平射线需要旋转的角度
    -- 由于setRotation是顺时针旋转的，因此需要取反
    local angle = -calcAngle(fromPos, toPos);   

	-- 播放动画
	local node = cc.Node:create();
	effectParent:addChild(node);
	
    local duration, effect = playEffect(node, linkEffectId);
    node:setPosition(targetPos.x, targetPos.y);
    
    local delay = cc.DelayTime:create(0.5);
    local callfunc = cc.CallFunc:create(function()
        node:removeFromParent();
    end);

    node:runAction(cc.Sequence:create(delay, callfunc));

    if linkEffectId == 342 then
        -- 闪电链纠正
        node:setRotation(angle);
        
        -- 光效x轴方向长度
        local xLength = 280;
        
        -- 根据距离进行缩放
        local scaleX = cc.pGetDistance(fromPos, toPos) / xLength;
        node:setScaleX(scaleX);
        
        duration = 0.05;
    end
    
    return duration * self.linkCount;
end

return LinkAction;